package com.cyh.blog.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cyh.blog.business.service.SysUserService;
import com.cyh.blog.business.vo.UserVo;
import com.cyh.blog.framework.object.PageResult;
import com.cyh.blog.persistence.beans.SysUser;
import com.cyh.blog.util.MD5Util;
import com.cyh.blog.util.Result;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestUserController {

    @Autowired
    private SysUserService sysUserService;




    @RequiresPermissions("user")
    @PostMapping("/list")
    public PageResult user(UserVo userVo) {
        PageInfo<SysUser> pageInfo = sysUserService.selectByCondition(userVo);
        return Result.tablePage(pageInfo);
    }

    @PostMapping("/add")
    public Result add(SysUser sysUser) {
        SysUser u = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("username", sysUser.getUsername()));
        if (u != null){
            return Result.error("用户名["+sysUser.getUsername()+"]已存在,请更换");
        }
        //密码加密
        sysUser.setPassword(MD5Util.MD5(sysUser.getPassword(), sysUser.getUsername()));
        sysUserService.insert(sysUser);
        return Result.success("添加成功");
    }

    @PostMapping("/get/{id}")
    public Result user(@PathVariable("id") Integer id) {
        SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("id", id));
        return Result.success("获取成功").add("data", sysUser);
    }

    @PostMapping("/edit")
    public Result user(SysUser sysUser) {
        try {
            sysUserService.updateById(sysUser);
        }catch (Exception e){
            return  Result.error("更新失败");
        }
        return Result.success("更新成功");
    }

    @PostMapping("/remove")
    public Result remove(Integer[] ids) {
        try {
            if(ids != null){
                for (int i=0; i<ids.length; i++){
                    sysUserService.deleteById(ids[i]);
                }
            }
        }catch (Exception e){
            return Result.error("删除失败");
        }

        return Result.success("成功删除"+ids.length+"条记录");
    }

}
